package com.jbl.st.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jbl.exceptionhandler.ManagerException;
import com.jbl.st.entity.CourseclassStudent;
import com.jbl.st.entity.Student;
import com.jbl.st.entity.StudentInfo;
import com.jbl.st.entity.dto.StudentQuery;
import com.jbl.st.entity.vo.StudentVO;
import com.jbl.st.excel.ExcelStudentListener;
import com.jbl.st.excel.StudentData;
import com.jbl.st.mapper.StudentMapper;
import com.jbl.st.service.CourseclassStudentService;
import com.jbl.st.service.StudentInfoService;
import com.jbl.st.service.StudentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jbl.te.entity.Department;
import com.jbl.te.entity.Departmentclass;
import com.jbl.te.entity.Major;
import com.jbl.te.entity.User;
import com.jbl.te.service.DepartmentService;
import com.jbl.te.service.DepartmentclassService;
import com.jbl.te.service.MajorService;
import com.jbl.te.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jbl
 * @since 2020-12-11
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    @Autowired
    StudentInfoService infoService;
    @Autowired
    DepartmentclassService classService;
    @Autowired
    DepartmentService departmentService;
    @Autowired
    MajorService majorService;
    @Autowired
    CourseclassStudentService courseclassStudentService;
    @Autowired
    UserService userService;


    @Override
    public void pageQuery(Page<Student> pageParam, StudentQuery studentQuery) {
        if (studentQuery == null) {
            this.page(pageParam,null);
            return;
        }

        QueryWrapper<Student> wrapper = new QueryWrapper<>();
        QueryWrapper<StudentInfo> infoQueryWrapper = new QueryWrapper<>();

        String studentNumber = studentQuery.getStudentNumber();
        String name = studentQuery.getName();
        String departmentId = studentQuery.getDepartmentId();

        if(!StringUtils.isEmpty(departmentId)) {
            wrapper.eq("department_id",departmentId);
        }
        if(!StringUtils.isEmpty(studentNumber)) {
            wrapper.likeRight("student_number",studentNumber);
        }
        if(!StringUtils.isEmpty(name)) {
            infoQueryWrapper.likeRight("name",name);
            infoQueryWrapper.select("id");
            List<StudentInfo> infoList = infoService.list(infoQueryWrapper);
            ArrayList<String> idList = new ArrayList<>();
            for (StudentInfo info : infoList) {
                idList.add(info.getId());
            }
            if(!idList.isEmpty()) {
                wrapper.in("id",idList);
            } else {
                wrapper.eq("id","");
            }
        }

        this.page(pageParam,wrapper);
    }

    @Override
    public StudentVO getStudentById(String id) {
        Student student = this.getById(id);
        if(student == null) {
            throw new ManagerException(20001,"学生不存在！");
        }
        StudentVO vo = new StudentVO();
        BeanUtils.copyProperties(student,vo);
        StudentInfo info = infoService.getById(student.getId());
        BeanUtils.copyProperties(info,vo);

        Department department = departmentService.getById(student.getDepartmentId());
        vo.setDepartmentId(department.getId());
        vo.setDepartmentName(department.getName());
        vo.setCollegeId(department.getCollegeId());

        Major major = majorService.getById(student.getMajorId());
        vo.setMajorId(major.getId());
        vo.setMajorName(major.getName());

        Departmentclass departmentclass = classService.getById(student.getDepartmentclassId());
        vo.setDepartmentclassId(departmentclass.getId());
        vo.setDepartmentclassName(departmentclass.getName());
        return vo;
    }

    @Override
    public boolean updateStudent(StudentVO vo) {
        Student student = this.getById(vo.getId());
        BeanUtils.copyProperties(vo,student);
        StudentInfo info = infoService.getById(student.getId());
        BeanUtils.copyProperties(vo,info);

        StringBuilder number = new StringBuilder(); //拼接学号

        SimpleDateFormat sformat = new SimpleDateFormat("yyyy-MM-dd");//日期格式
        number.append(sformat.format(info.getHiredate()).substring(2,4)); //入职年份后2号
        //系序号，2位
        QueryWrapper<Department> departmentQueryWrapper = new QueryWrapper<>();
        departmentQueryWrapper.orderByAsc("gmt_create");
        List<Department> departmentList = departmentService.list(departmentQueryWrapper);
        for (Integer i = 0;i < departmentList.size();i++) {
            if(departmentList.get(i).getId().equals(student.getDepartmentId())) {
                if(i < 10) {
                    number.append("0");
                } number.append(i.toString());
            }
        }
        //专业序号，2位
        QueryWrapper<Major> majorQueryWrapper = new QueryWrapper<>();
        majorQueryWrapper.orderByAsc("gmt_create");
        List<Major> majorList = majorService.list(majorQueryWrapper);
        for (Integer i = 0;i < majorList.size();i++) {
            if(majorList.get(i).getId().equals(student.getMajorId())) {
                if(i < 10) {
                    number.append("0");
                } number.append(i.toString());
            }
        }
        //行政班序号，2位
        QueryWrapper<Departmentclass> departmentclassQueryWrapper = new QueryWrapper<>();
        departmentclassQueryWrapper.orderByAsc("gmt_create");
        List<Departmentclass> departmentclassList = classService.list(departmentclassQueryWrapper);
        for (Integer i = 0;i < departmentclassList.size();i++) {
            if(departmentclassList.get(i).getId().equals(student.getDepartmentclassId())) {
                if(i < 10) {
                    number.append("0");
                } number.append(i.toString());
            }
        }
        //学生序号，3位
        Integer count = student.getOrderNumber();
        if (count < 10) number.append("0");
        number.append(count.toString());

        student.setStudentNumber(number.toString());

        boolean update = this.updateById(student);
        if(update) {
            boolean update1 = infoService.updateById(info);
            //修改用户名
            User user = userService.getById(student.getId());
            user.setUsername(student.getStudentNumber());
            boolean update2 = userService.updateById(user);
            return update1 && update2;
        }

        return update;
    }

    @Override
    public Boolean removeStudentById(String id) {
        //删除课程班学生中间表
        QueryWrapper<CourseclassStudent> wrapper = new QueryWrapper<>();
        wrapper.eq("student_id",id);
        courseclassStudentService.remove(wrapper);
        //删除info
        infoService.removeById(id);
        //删除学生用户
        userService.removeById(id);
        boolean b = this.removeById(id);
        return b;
    }

    @Override
    public void saveStudentByExcel(MultipartFile file, StudentService studentService, StudentInfoService infoService, DepartmentService departmentService, MajorService majorService, DepartmentclassService classService, UserService userService) {
        try {
            InputStream inputStream = file.getInputStream();
            EasyExcel.read(inputStream, StudentData.class, new ExcelStudentListener(studentService,infoService,departmentService,majorService,classService,userService))
                    .sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
            throw new ManagerException(20001,"添加失败！");
        }
    }
}
